/*
 * @copyright fxsen <br/>
 * @date 2022/3/30 15:52 <br/>
 * @email <a href="mailto:fxsen@foxmail.com">
 * @author fxsen
 */
package com.fxsen.commons.web.core.config;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.fxsen.commons.core.base.common.entity.JwtUser;
import com.fxsen.commons.core.constant.Constants;
import com.fxsen.commons.utils.ContextUtils;
import com.fxsen.commons.utils.CurrentTokenThreadLocalUtils;
import com.fxsen.commons.utils.JwtUtils;
import com.fxsen.commons.utils.LoggerUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * mybatis自动注入配置
 * @author fxsen
 * @date 2022/3/30 15:52
 * @email <a href="mailto:fxsen@foxmail.com">
 */
@Component
public class MyMetaObjectConfig implements MetaObjectHandler {
    private String getToken(){
        String token = CurrentTokenThreadLocalUtils.getValue();
        if(StringUtils.isBlank(token)){
            ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
            RequestContextHolder.setRequestAttributes(servletRequestAttributes,true);//设置子线程共享
            if (null != servletRequestAttributes) {
                HttpServletRequest request = servletRequestAttributes.getRequest();
                token = request.getHeader(JwtUtils.JWT_HEADER_KEY);
                if (StringUtils.isBlank(token)){
                    // 如果令牌为空, 再取Cookie中X-Token
                    Cookie[] cookies = request.getCookies();
                    if (cookies != null) {
                        for (Cookie cookie : cookies) {
                            if (JwtUtils.JWT_HEADER_KEY.equals(cookie.getName())) {
                                token = cookie.getValue();
                                break;
                            }
                        }
                    }
                }
                if (StringUtils.isBlank(token)){
                    token = (String) request.getSession().getAttribute(JwtUtils.JWT_HEADER_KEY);
                }
                if (StringUtils.isBlank(token)){
                    // 如果令牌为空, 再取QueryString中token
                    token = request.getParameter(JwtUtils.JWT_HEADER_KEY);
                }
            }
        }
        return token;
    }
    /**
     * 插入
     * @param metaObject 元素对象
     */
    @Override
    public void insertFill(MetaObject metaObject) {
        try {
            JwtUser user = JwtUtils.getParamByToken(getToken());
            String userId = StringUtils.isNotBlank(user.getUserId()) ? user.getUserId() : null;
            this.strictInsertFill(metaObject, "createBy", String.class,userId);
        }catch (Exception e){
            e.printStackTrace();
            LoggerUtils.error("统一新增，加入用户id出错",e);
        }
        this.strictInsertFill(metaObject, "createDate", Date.class, new Date());
        this.strictInsertFill(metaObject, "status", Integer.class, Constants.STATUS_YES);
        this.strictInsertFill(metaObject, "deleteLogic", Integer.class, Constants.NO_DELETE);
    }

    /**
     * 更新
     * @param metaObject 元素对象
     */
    @Override
    public void updateFill(MetaObject metaObject) {
        try {
            JwtUser user = JwtUtils.getParamByToken(getToken());
            String userId = StringUtils.isNotBlank(user.getUserId()) ? user.getUserId() : null;
            this.strictUpdateFill(metaObject, "updateBy", String.class, userId);
        }catch (Exception e){
            e.printStackTrace();
            LoggerUtils.error("统一更新，加入用户id出错",e);
        }
        this.strictUpdateFill(metaObject, "updateDate", Date.class, new Date());
    }
}
